#include "osal/string.h"
#include "custom_mem/custom_mem.h"
#include "stream_frame.h"
#include "osal/task.h"
#include "dev/usb/uvc_host.h"
#include "osal/task.h"

#define AUDIO_LEN  (1024)
struct os_task send_usbspk_audio_task;

static int opcode_func(stream *s,void *priv,int opcode)
{
	int res = 0;
	//_os_printf("%s:%d\topcode:%d\n",__FUNCTION__,__LINE__,opcode);
	switch(opcode)
	{
		case STREAM_OPEN_ENTER:
		break;
		case STREAM_OPEN_EXIT:
		{
            enable_stream(s,1);
		}
		break;
		case STREAM_OPEN_FAIL:
		break;
		default:
			//默认都返回成功
		break;
	}
	return res;
}

void send_usbspk_audio(void *d)
{
    struct data_structure *get_f = NULL;
    stream* s = NULL;
    volatile int16 *buf = NULL;
    uint32 len = 0;
    volatile uint8 *audio_addr = NULL;
	UAC_MANAGE *usbspk_manage = NULL;
	
    s = open_stream_available(R_USB_SPK,0,8,opcode_func,NULL);
    if(!s)
    {
        os_printf("open usbspk stream err\n");
    }
    while(1)
    {
		if(!usbspk_manage)
			usbspk_manage = get_usbspk_new_frame(0);
		if(usbspk_manage) {
			get_f = recv_real_data(s);
			if(get_f)
			{
				buf = get_stream_real_data(get_f);
				len = get_stream_real_data_len(get_f); 
				audio_addr = get_uac_frame_data(usbspk_manage);
				os_memcpy((uint8*)audio_addr, buf, len);
				set_uac_frame_datalen(usbspk_manage, len);
				set_uac_frame_sta(usbspk_manage, 1);
				put_usbspk_frame_to_use(usbspk_manage);
				usbspk_manage = NULL;
				free_data(get_f);
			} 
		}  
		os_sleep_ms(10);   
    }
}

void usbspk_audio_init(void)
{
	static uint8 usbspk_init_flag = 0;
	if(usbspk_init_flag == 0) {
		OS_TASK_INIT("send_usbspk_audio", &send_usbspk_audio_task, send_usbspk_audio, NULL, OS_TASK_PRIORITY_NORMAL, 512);
		usbspk_room_init();
		usbspk_init_flag = 1;
	}
}